package org.codegallery.jpagal.service.impl;

import java.util.List;

import org.codegallery.jpagal.entity.Customer;
import org.codegallery.jpagal.service.CustomerService;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

public class CustomerServiceHbImpl implements CustomerService {
	private SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Customer save(Customer customer) {
		Session session=sessionFactory.getCurrentSession();
		if (customer.getId() == null) {
			session.persist(customer);
			return customer;
		} else {
			return (Customer)session.merge(customer);
		}
	}

	public List<Customer> findByFirstname(String firstname) {
		Session session=sessionFactory.getCurrentSession();
		Criteria criteria=session.createCriteria(Customer.class);
		criteria.add(Restrictions.eq("firstname", firstname));
		return criteria.list();
	}

}